﻿using FCModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FCBLL
{
    public class KFBomConvertBLL
    {
        public static string start = "EE";
        /// <summary>
        /// 根据ds获取开发BOM数据
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        public static List<KFBom> CreateKFBOMByxlsx(DataSet ds)
        {
            string stHALB = "";
            string mainName = ds.Tables[0].Rows[2][13].ToString().Split('：')[1];
            int mainCount = Convert.ToInt32(SAPBOMConvertBLL.getPanelCntByOutPrdName(mainName));
            List<KFBom> KFbomList = new List<KFBom>();
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                DataTable dt = ds.Tables[i];
                int current = Convert.ToInt32(SAPBOMConvertBLL.getPanelCntByOutPrdName(dt.Rows[2][13].ToString().Split('：')[1]));
                int _d = current / mainCount;
                if (i == 0)
                {
                    KFBom mainSheet = new KFBom();
                    string[] desc = { "2ND", "1ST" };
                    KFBOMdao s2dao = new KFBOMdao();
                    List<KFBOMdao> KFBOMS1S2 = getKFS1S2(ds, desc, mainCount, out s2dao, out stHALB);//out S2BomCom,
                    KFBOMdao ma_d = new KFBOMdao();
                    List<KFBOMdao> KFBOM_D = getKF_D(ds, s2dao, mainCount, out ma_d);
                    List<KFBOMdao> KFBomMain = getMainKFBom(ds, ma_d);

                    List<KFBOMdao> mainSheetList = KFBomMain.Union(KFBOM_D).Union(KFBOMS1S2).ToList<KFBOMdao>();
                    //除以主板数量
                    mainSheet.title = getKFBomTitleFromSheet(ds.Tables[i]);
                    mainSheet.BomList = mainSheetList;
                    //mainSheet.BomList = OrderByKFBomList(KFBomMain.Union(KFBOM_D).Union(KFBOMS1S2).ToList<KFBOMdao>(), stHALB);

                    mainSheet.dt = CommonBLL.ToDataSet<KFBOMdao>(mainSheet.BomList).Tables[0];
                    mainSheet.dt.TableName = dt.TableName.Replace("'", "").Replace("$", "");
                    mainSheet.BomVersion = getBomVersionByDataTable(dt);// dt.Rows[dt.Rows.Count - 1][0].ToString();//bomversion;
                    KFbomList.Add(mainSheet);
                }
                else
                {
                    KFBom BomSheet = new KFBom();
                    BomSheet.title = getKFBomTitleFromSheet(ds.Tables[i]);
                    List<KFBOMdao> bomlist = new List<KFBOMdao>();
                    int prono = 10;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        bool _Dbegin = false;
                        if (dt.Rows[j][13].ToString().ToUpper().Contains("FER"))
                        {
                            _Dbegin = true;
                            bomlist.Add(getKFBomDaoFromdt(dt, j));
                            KFBOMdao s_d = new KFBOMdao();
                            s_d.num = "1";
                            s_d.BOMProjectNO = prono.ToString("0000");
                            s_d.BOMComponent = start + dt.Rows[2][13].ToString().Split('：')[1] + "-D";
                            s_d.ComponentNum = _d.ToString(); ;
                            s_d.AssembGrade = "2";
                            s_d.Area = "1";
                            s_d.EngDesc = dt.Rows[2][13].ToString().Split('：')[1] + " DIP HALB";
                            s_d.ChineseDesc = dt.Rows[2][13].ToString().Split('：')[1] + " DIP半成品";
                            bomlist.Add(s_d);
                        }
                        if (dt.Rows[j][13].ToString().ToUpper().Contains("HALB"))
                        {
                            _Dbegin = false;
                        }
                        if (_Dbegin)
                        { }
                    }
                    //除以主板数量
                    BomSheet.BomList = bomlist;
                    BomSheet.dt = CommonBLL.ToDataSet<KFBOMdao>(BomSheet.BomList).Tables[0];
                    BomSheet.dt.TableName = dt.TableName.Replace("'", "").Replace("$", "");

                    BomSheet.BomVersion = getBomVersionByDataTable(dt);// dt.Rows[dt.Rows.Count - 1][0].ToString(); ;

                    KFbomList.Add(BomSheet);
                }
            }
            return KFbomList;
        }

        /// <summary>
        /// 获取开发BOM的所有_D
        /// </summary>
        /// <param name="ds"></param>
        /// <param name="S2BOMComponent"></param>
        /// <returns></returns>
        public static List<KFBOMdao> getKF_D(DataSet ds, KFBOMdao s2dao, int mainCount, out KFBOMdao ma_d)
        {
            List<KFBOMdao> KFBomList = new List<KFBOMdao>();
            int prono = 10;
            ma_d = new KFBOMdao();
            ma_d.BOMComponent = start + ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + "-D";
            ma_d.EngDesc = ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + " 2ND DIP ictitious HALB";
            ma_d.ChineseDesc = ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + " 2ND DIP半成品";
            KFBomList.Add(ma_d);
            for (int k = 0; k < ds.Tables.Count; k++)
            {
                DataTable dt = ds.Tables[k];
                int current = Convert.ToInt32(SAPBOMConvertBLL.getPanelCntByOutPrdName(dt.Rows[2][13].ToString().Split('：')[1])) / mainCount;
                //int _d = current / mainCount;
                bool S1begin = false;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i][13].ToString().ToUpper().Contains("FER"))
                    {
                        S1begin = true;
                        continue;
                    }
                    if (dt.Rows[i][13].ToString().ToUpper().Contains("HALB"))
                    {
                        S1begin = false;
                    }
                    if (S1begin)
                    {
                        KFBOMdao s_d = getKFBomDaoFromdt(dt, i, current);
                        s_d.BOMProjectNO = prono.ToString("0000");
                        KFBomList.Add(s_d);
                        prono += 10;
                    }
                }
                if (k != 0)
                {
                    KFBOMdao _d = new KFBOMdao();
                    _d.BOMComponent = start + dt.Rows[2][13].ToString().Split('：')[1] + "-D";
                    _d.num = "1";
                    //Int32.Parse(getPanelCntByOutPrdName(dt.Rows[2][13].ToString().Split('：')[1])) * -1).ToString()
                    _d.ComponentNum = (Int32.Parse(SAPBOMConvertBLL.getPanelCntByOutPrdName(dt.Rows[2][13].ToString().Split('：')[1])) * -1 / mainCount).ToString();// "-1";
                    _d.AssembGrade = "3";
                    _d.Area = "1";
                    _d.BOMProjectNO = prono.ToString("0000");
                    _d.EngDesc = dt.Rows[2][13].ToString().Split('：')[1] + " DIP ictitious HALB";
                    _d.ChineseDesc = dt.Rows[2][13].ToString().Split('：')[1] + " DIP半成品";
                    KFBomList.Add(_d);
                    prono += 10;
                }
            }
            s2dao.num = "1";
            s2dao.BOMProjectNO = prono.ToString("0000");
            s2dao.ComponentNum = "1";
            s2dao.AssembGrade = "3";
            s2dao.Area = "1";
            KFBomList.Add(s2dao);
            return KFBomList;
        }

        /// <summary>
        /// 获取开发BOM的S1和S2
        /// </summary>
        /// <param name="ds">EXCEL表单中所有的sheet</param>
        /// <param name="descs">1st,2ND</param>
        /// <param name="S2BOMComponent">返回S2bom组件值</param>
        /// <returns></returns>
        public static List<KFBOMdao> getKFS1S2(DataSet ds, string[] descs, int mainCount, out KFBOMdao s2dao, out string stHALB)
        {
            stHALB = "";
            List<KFBOMdao> KFBomList = new List<KFBOMdao>();
            string S1BOMComponent = start + ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + "-S1";
            string S1Engdesc = ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + " 1ST SMT HALB";
            string S1CNdesc = ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + " 1ST 半成品";

            string S2BOMComponent = start + ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + "-S2";
            string S2Engdesc = ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + " 2ND SMT HALB";
            string S2CNdesc = ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + " 2ND 半成品";

            s2dao = new KFBOMdao();
            s2dao.BOMComponent = S2BOMComponent;
            s2dao.EngDesc = ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + " 2ND SMT HALB";
            s2dao.ChineseDesc = ds.Tables[0].Rows[2][13].ToString().Split('：')[1] + " 2ND 半成品";
            KFBomList.Add(s2dao);
            int childNO = 10;
            //string stHALB = "";
            foreach (string desc in descs)
            {
                if (desc.Contains("2"))
                {
                    KFBOMdao s2 = new KFBOMdao();
                    s2.BOMComponent = S2BOMComponent;
                    s2.ChineseDesc = S2CNdesc;
                    s2.EngDesc = S2Engdesc;
                    KFBomList.Add(s2);
                    childNO = 10;
                }
                if (desc.Contains("1"))
                {
                    KFBOMdao s1child = new KFBOMdao();
                    s1child.BOMComponent = S1BOMComponent;
                    s1child.EngDesc = S1Engdesc;
                    s1child.ChineseDesc = S1CNdesc;
                    KFBomList.Add(s1child);
                    childNO = 10;
                }
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    DataTable dt = ds.Tables[i];
                    if (dt.TableName == "flowchart") continue;
                    string outprdno = ds.Tables[i].Rows[2][13].ToString().Split('：')[1];
                    int outprdnoQty = Convert.ToInt32(SAPBOMConvertBLL.getPanelCntByOutPrdName(outprdno));
                    outprdnoQty = outprdnoQty / mainCount;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        if (dt.Rows[j][13].ToString().ToUpper().Contains(desc))
                        {
                            KFBOMdao s1child = getKFBomDaoFromdt(dt, j, outprdnoQty);
                            s1child.ComponentNum = "1";
                            s1child.AssembGrade = "4";
                            s1child.Area = "0";
                            s1child.num = "1";
                            s1child.BOMProjectNO = childNO.ToString("0000");
                            KFBomList.Add(s1child);
                            childNO += 10;
                        }
                    }
                }

                if (desc.Contains("2"))
                {
                    KFBOMdao s2s1 = new KFBOMdao();
                    s2s1.num = "1";
                    s2s1.BOMProjectNO = childNO.ToString("0000");
                    s2s1.BOMComponent = S1BOMComponent;
                    s2s1.ComponentNum = "1";
                    s2s1.AssembGrade = "4";
                    s2s1.Area = "1";
                    s2s1.EngDesc = S1Engdesc;
                    s2s1.ChineseDesc = S1CNdesc;
                    KFBomList.Add(s2s1);
                }
            }


            foreach (string desc in descs)
            {
                for (int i = 0; i < ds.Tables.Count; i++)
                {
                    DataTable dt = ds.Tables[i];
                    if (dt.TableName == "flowchart") continue;
                    string partNO = "";
                    bool S1begin = false;
                    string outprdno = ds.Tables[i].Rows[2][13].ToString().Split('：')[1];//.Replace("产品名称：", "").Replace(":", "");
                    int outprdnoQty = Convert.ToInt32(SAPBOMConvertBLL.getPanelCntByOutPrdName(outprdno));
                    outprdnoQty = outprdnoQty / mainCount;
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        if (dt.Rows[j][13].ToString().ToUpper().Contains(desc))
                        {
                            S1begin = true;
                            partNO = dt.Rows[j][8].ToString();
                            KFBOMdao HALB = getKFBomDaoFromdt(dt, j, outprdnoQty);

                            KFBomList.Add(HALB);
                            if (i == 0 && desc.Contains("1"))
                            {
                                stHALB = HALB.BOMComponent;
                            }
                            continue;
                        }
                        if (string.IsNullOrWhiteSpace(dt.Rows[j][2].ToString()))
                        {
                            S1begin = false;
                        }
                        if (S1begin)
                        {
                            KFBomList.Add(getKFBomDaoFromdt(dt, j, outprdnoQty));
                        }
                    }
                }
            }

            ////严总，应该是在这里改一下就好了，在这里乘那个参数
            //int num = 1;
            //num =Convert.ToInt32(SAPBOMConvertBLL.getPanelCntByOutPrdName("***"));
            //foreach (KFBOMdao kfBom in KFBomList) 
            //{

            //    kfBom.ComponentNum = (Convert.ToInt32(kfBom.ComponentNum) * num).ToString();
            //}

            return KFBomList;
        }

        public static string getBomVersionByDataTable(DataTable dt)
        {
            string bomVersion = "";
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                if (string.IsNullOrWhiteSpace(dt.Rows[i][0].ToString())) continue;
                bomVersion = dt.Rows[i][0].ToString();
                break;
            }
            return bomVersion;
        }

        //public static List<KFBOMdao> OrderByKFBomList(List<KFBOMdao> KFBomList, string stHALB) 
        //{
        //    int k = 0;
        //    foreach (var sw in KFBomList)
        //    {
        //        if (sw.layOut == null)
        //            sw.layOut = "";
        //    }
        //    List<KFBOMdao> startWith = KFBomList.Where(p => p.layOut != null && p.layOut.StartsWith(@"_")).ToList<KFBOMdao>();
        //    KFBomList.RemoveAll(p => p.layOut.StartsWith(@"_"));
        //    for (int i = 0; i < KFBomList.Count; i++) 
        //    {
        //        KFBOMdao dao = KFBomList[i];
        //        if (dao.BOMComponent.Equals(stHALB) && dao.BOMProjectNO.Equals(""))
        //        {
        //            k = i+1;
        //        }
        //    }
        //    foreach (var sw in startWith)
        //    {
        //        KFBomList.Insert(k, sw);
        //    }
        //    return KFBomList;
        //}

        /// <summary>
        /// 根据Table的一行获取KFBom的一行
        /// </summary>
        /// <param name="dt">导入DataTable的表单</param>
        /// <param name="row">某一行</param>
        /// <returns>KFBom的一行</returns>
        public static KFBOMdao getKFBomDaoFromdt(DataTable dt, int row, int baseQty = 1)
        {
            KFBOMdao KFdao = new KFBOMdao();
            KFdao.BomPartNo = dt.Rows[row][0].ToString();  //BOM料号
            KFdao.num = dt.Rows[row][1].ToString();        //基本数量  
            KFdao.BOMProjectNO = dt.Rows[row][2].ToString();//BOM项目号
            KFdao.ProjectType = dt.Rows[row][3].ToString();     //项目类别
            KFdao.ReplaceStr = dt.Rows[row][4].ToString();     //替代策略
            KFdao.ReplaceGroup = dt.Rows[row][5].ToString();   //替代组
            KFdao.ReplacePro = dt.Rows[row][6].ToString();     //替代优先级
            KFdao.UsePossibility = dt.Rows[row][7].ToString();  //使用可能性%
            KFdao.BOMComponent = dt.Rows[row][8].ToString();    //BOM组件
            KFdao.ComponentNum = String.IsNullOrWhiteSpace(dt.Rows[row][9].ToString()) ? "" : (Int32.Parse(dt.Rows[row][9].ToString()) * baseQty).ToString();     //组件数量
            KFdao.AssembGrade = dt.Rows[row][10].ToString();     //装备级数
            KFdao.layOut = SAPBOMConvertBLL.replaceLongItem(dt.Rows[row][11].ToString());//装配图纸编(位)号
            KFdao.Area = dt.Rows[row][12].ToString(); //区域 (排序字符串)
            KFdao.EngDesc = dt.Rows[row][13].ToString();     //英文物料描述
            KFdao.ChineseDesc = dt.Rows[row][14].ToString();//中文物料描述
            KFdao.manufacturer = dt.Rows[row][15].ToString(); //制造商
            KFdao.manufacturerNo = dt.Rows[row][16].ToString(); //制造商编号
            KFdao.SendAddress = dt.Rows[row][17].ToString(); //发货地点
            KFdao.Remark = dt.Rows[row][18].ToString(); //备注
            return KFdao;
        }

        /// <summary>
        /// 根据导入的EXCEL格式获取KFBom的表单头
        /// </summary>
        /// <param name="dt">导入excel的表单</param>
        /// <returns>KFBom的表单头</returns>
        public static KFBomTitle getKFBomTitleFromSheet(DataTable dt)
        {
            KFBomTitle Title = new KFBomTitle();
            Title.PartNO = dt.Rows[2][0].ToString();     //产品编号
            Title.FileVersion = dt.Rows[2][8].ToString();//文件版本
            Title.ProductName = dt.Rows[2][13].ToString(); //产品名称
            Title.ComUseReplace = dt.Rows[2][15].ToString();   //工厂/用途/替代
            Title.ComUseReplaceValue = dt.Rows[2][16].ToString();
            Title.ProductDesc = dt.Rows[3][0].ToString();     //产品描述
            Title.Customer = dt.Rows[3][13].ToString();      //客户名称
            Title.UpdateDate = dt.Rows[3][15].ToString();
            return Title;
        }

        public static List<KFBOMdao> getMainKFBom(DataSet ds, KFBOMdao kfdao)
        {
            List<KFBOMdao> KFBomList = new List<KFBOMdao>();

            KFBOMdao main = new KFBOMdao();
            main = getKFBomDaoFromdt(ds.Tables[0], 5);
            KFBomList.Add(main);
            KFBOMdao ma_d = new KFBOMdao();
            ma_d.BOMComponent = kfdao.BOMComponent;
            ma_d.ChineseDesc = kfdao.ChineseDesc;
            ma_d.EngDesc = kfdao.EngDesc;
            ma_d.BOMProjectNO = "0010";
            ma_d.ComponentNum = "1";
            ma_d.AssembGrade = "2";
            KFBomList.Add(ma_d);

            return KFBomList;
        }

    }
}
